﻿/*   
    Copyright (C) 2009 Galaktika Corporation ZAO

    This file is a part of Galaktika.BusinessMonitor
 
    Galaktika.BusinessMonitor is a free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    You should have received a copy of the GNU General Public License
    along with Galaktika.BusinessMonitor.  If not, see <http://www.gnu.org/licenses/>.
  
    If GPL v.3 is not suitable for your products or company,
    Galaktika Corp provides Galaktika.BusinessMonitor under a flexible commercial license
    designed to meet your specific usage and distribution requirements.
    If you have already obtained a commercial license from Galaktika Corp,
    you can use this file under those license terms.
*/

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Ranet.AgOlap.Controls;
using Galaktika.BI.Runtime.Services;
using System.ComponentModel;
using Galaktika.BI.Silverlight.Controls.General;
using System.Threading;
using System.Collections.Generic;
using Galaktika.BI.Runtime;
using Ranet.AgOlap.Controls.General;
using Galaktika.BI.Extensibility.Dom;
using Ranet.AgOlap.Controls.General.ClientServer;
using Ranet.AgOlap.Commands;
using Ranet.Olap.Core;
using Ranet.Olap.Core.Metadata;

namespace Galaktika.BI.Silverlight.Controls.LevelChoice
{
    public class LevelChoicePopUpEx : LevelChoicePopUp, IBindableObject, IEditableObject
    {
        public LevelChoicePopUpEx()
        {
            Height = 18;
            MaxHeight = 18;
            MinHeight = 18;
            //PopUpContainer.SelectedItemTextBox.FontSize = 11;
        }

        protected override void BeforePopUp()
        {
            base.BeforePopUp();

            OlapDataLoaderEx loader = new OlapDataLoaderEx(this);
            loader.Context = this.Context;
            ChoiceControl.OlapDataLoader = loader;
        }

        protected override LevelChoiceCtrl GetChoiceControl()
        {
            LevelChoiceCtrl ctrl = base.GetChoiceControl();
            if (m_Context != null)
            {
                ctrl.LogManager = new LogManagerEx(m_Context);
            }
            return ctrl;
        }

        protected override void ApplySelection()
        {
            base.ApplySelection();

            try
            {
                //Сохраняем в глобальную переменную
                IUserTaskManager taskManager = (IUserTaskManager)Context.Services.GetService(typeof(IUserTaskManager));
                if (taskManager != null)
                {
                    taskManager.RunTaskAsync(String.Format(Localization.AppTask_ModificationVariable, AVariableToLevel), state => ModifyVariable(state), ChoiceControl.SelectedInfo);
                    //ThreadPool.QueueUserWorkItem(new WaitCallback(
                    //    state => context.ModifyVariable(this.Context, AVariableToLevel, uniqueName)));
                }
            }
            catch (Exception ex)
            {
                LogManager.LogException(this.Name, ex);
            }

        }

        private void ModifyVariable(object state)
        {
            LevelInfo levelInfo = (LevelInfo)state;

            String uniqueName = String.Empty;
            String caption = String.Empty;
            if (levelInfo != null)
            {
                uniqueName = levelInfo.UniqueName;
                caption = levelInfo.Caption;
            }

            String variableName = AVariableToLevel;
            IExecutionContext context = (IExecutionContext)this.Context.Services.GetService(typeof(IExecutionContext));
            if (context != null && !String.IsNullOrEmpty(variableName))
            {
                BrickVariable variable = context.GetVariable(this.Context, variableName);
                if (variable != null)
                {
                    context.ModifyVariable(this.Context, variableName, uniqueName);
                    variable.UserData[uniqueName] = caption;
                }
            }
        }

        private String m_VariableToLevel = String.Empty;
        /// <summary>
        /// Глобальная переменная для уровня
        /// </summary>
        public String AVariableToLevel
        {
            set
            {
                m_VariableToLevel = value;
            }
            get
            {
                return m_VariableToLevel;
            }
        }


        #region IEditableObject Members

        public void BeginEdit()
        {
        }

        public void CancelEdit()
        {
        }

        public void EndEdit()
        {
            //NeedReload = true;
            IExecutionContext context = (IExecutionContext)this.Context.Services.GetService(typeof(IExecutionContext));
            if (context != null)
            {
                //Из глобальной переменной читаем имя выбранного 
                BrickVariable variable = context.GetVariable(this.Context, AVariableToLevel);
                if (variable != null)
                {
                    String value = variable.CurrentValue.Trim();
                    if (!String.IsNullOrEmpty(value))
                    {
                        //Пробуем найти в КЭШ Caption по имени
                        if (variable.UserData != null && variable.UserData.ContainsKey(value) && variable.UserData[value] is String)
                        {
                            PopUpContainer.Text = (String)variable.UserData[value];
                        }
                        else
                        {
                            // чтобы не моргало this.Dispatcher.BeginInvoke(delegate() { m_Popup.Text = String.Empty; });

                            OlapDataLoaderEx loader = new OlapDataLoaderEx(this);
                            loader.Context = this.Context;
                            loader.DataLoaded += new EventHandler<DataLoaderEventArgs>(loader_DataLoaded);
                            MetadataQuery args = CommandHelper.CreateGetLevelQueryArgs(AConnection, ACubeName, ADimensionUniqueName, AHierarchyUniqueName, value);
                            loader.LoadData(args, variable);
                        }
                        return;
                    }
                }
            }

            PopUpContainer.Text = String.Empty;
        }

        void loader_DataLoaded(object sender, DataLoaderEventArgs e)
        {
            PopUpContainer.Text = String.Empty;
            if (e.Result.ContentType == InvokeContentType.Error)
            {
                LogManager.LogMessage(this.Name, e.Result.Content);
                return;
            }

            if (String.IsNullOrEmpty(e.Result.Content))
                return;

            LevelInfo level = XmlSerializationUtility.XmlStr2Obj<LevelInfo>(e.Result.Content);
            if (level != null)
            {
                PopUpContainer.Text = level.Caption;

                BrickVariable variable = e.UserState as BrickVariable;
                if (variable != null)
                {
                    variable.UserData[level.UniqueName] = level.Caption;
                }
            }
        }

        #endregion

        #region IBindableObject Members

        IBindingContext m_Context = null;
        public IBindingContext Context
        {
            get
            {
                return m_Context;
            }
            set
            {
                m_Context = value;
                NeedReload = true;

                if (m_Context != null)
                {
                    base.LogManager = new LogManagerEx(m_Context);
                }
            }
        }


        private IDictionary<string, IBindingManager> m_Bindings;
        public IDictionary<string, IBindingManager> Bindings
        {
            get
            {
                if (m_Bindings == null)
                {
                    m_Bindings = new SafeDictionary<string, IBindingManager>();
                }

                return m_Bindings;
            }
        }

        #endregion
    }
}
